package com.awanp3.nimbus.common.business.util;

import com.awanp3.nimbus.common.core.constant.GlobalConstants;
import com.awanp3.nimbus.common.redis.utils.RedisUtils;
import com.awanp3.nimbus.common.business.enums.OrderNumberFormat;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 用于生成订单号和订单行项目
 *
 * @author 20014170
 */
public class OrderUtil {

    /**
     * 按单号模板生成订单号
     * @param format 单号格式
     * @return String 订单号
     */
    public static String generateOrderNumber(OrderNumberFormat format, String tenantId) {
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = currentDate.format(formatter);
        String redisKey = tenantId + ":" + GlobalConstants.SERIAL_NUMBER_KEY + format.getPrefix() + ":" + formattedDate;
        long sequence = 1;
        if (RedisUtils.hasKey(redisKey)) {
            sequence = RedisUtils.incrAtomicValue(redisKey);
        } else {
            RedisUtils.setCacheObject(redisKey, sequence, Duration.ofDays(1));
        }
        return String.format("%s%s%0" + format.getLength() + "d", format.getPrefix(), formattedDate, sequence);
    }

    /**
     * 生成行项目号
     * @param index 序列号
     * @return String 航项目号
     */
    public static String generateOrderItem(int index) {
        return String.format("%06d", index);
    }
}
